package fr.gestionimmo.util.jaas;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
*
* <p>The idea to use a PhaseListener for this was taken from
* Aaron L. Bartell on the JSF-developers mailing list.</p>
*/
public class ForcedLoginPhaseListener implements PhaseListener {

	protected final Log log = LogFactory.getLog(getClass());
	
	/** Creates a new instance of ForcedLoginPhaseListener */
	public ForcedLoginPhaseListener() {}
	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}
	
	public void afterPhase(PhaseEvent event) {
		
System.out.println("+++++ afterPhase ++++ ");		
		
		FacesContext context = event.getFacesContext();
		// Check to see if they are on the login page.
		boolean onLoginPage = (-1 != context.getViewRoot().getViewId().
				lastIndexOf("login")) ? true : false,isLoggedIn = false;
		try {			
			isLoggedIn = ForcedLoginFilter.checkLoginState(	(ServletRequest)context.getExternalContext().getRequest(),
				  											(ServletResponse)context.getExternalContext().getResponse()
				  										);
		}
		catch (Exception e) {
		  log.error("ForcedLoginPhaseListener : "+e.getMessage(), e);
		}
    if (!onLoginPage && !isLoggedIn) {
      context.getApplication().getNavigationHandler().
          handleNavigation(context, null, "login");
    }
  }
  public void beforePhase(PhaseEvent event) {
  }
}

